import requests, json, time, string, random
from datetime import datetime


class mhys:

    def __init__(self, user, pwd, url):
        self.user = user
        self.pwd = pwd
        self.url = url
        self.headers = {
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
            'Accept': "application/json, text/plain, */*",
            'Accept-Encoding': "gzip, deflate",
            'Content-Type': "application/json",
            'language': "zh",
            'Origin': "http://moot.mhys.com.cn",
            'Referer': "http://moot.mhys.com.cn/",
            'Accept-Language': "zh-CN,zh;q=0.9,en;q=0.8"
        }  # 请求头
        self.stuMsg = {}  # 学生信息
        self.courseData = []  # 课程信息
        self.chapterData = []  # 所有章节信息
        self.maxReteies = 5  # 最大尝试次数
        self.delay = 3  # 延迟时间

    def timestamp(self):
        """
        获取时间戳
        :return: 返回一个int 类型数字
        """
        return int(time.time())

    def login(self):
        """
        登录接口获取token
        :return: 返回布尔值确认是否登录成功
        """
        print("==========开始登录==========")
        url = f"{self.url}/sys/login"
        payload = json.dumps({
            "username": self.user,
            "password": self.pwd
        })
        retries = 0
        while retries < self.maxReteies:
            try:
                response = requests.post(url, data=payload, headers=self.headers, verify=False)
                if response.status_code == 200:
                    resp = response.json()
                    if resp["msg"] == "success":
                        print(f"获取到登录信息：{resp}")
                        self.headers["token"] = resp["data"]["token"]
                        return True
                    else:
                        print(resp)
                        return False
                else:
                    print(f"访问出现问题：code:{response.status_code},Msg:{response.text}")
                    return False
            except requests.exceptions.RequestException as e:
                print(f"请求失败，错误信息：{e}")
                retries += 1
                if retries < self.maxReteies:
                    print(f"等待{self.delay}秒后重试...")
                    time.sleep(self.delay)
                else:
                    print("打到最大重试次数，请求失败")
                    return False

    def get_CenterInfo(self):
        """
        获取学生信息
        :return:
        """
        print("==========获取用户信息==========")
        url = f"{self.url}/center/getCenterInfo?_t={self.timestamp()}"
        retries = 0
        while retries < self.maxReteies:
            try:
                response = requests.get(url, headers=self.headers, verify=False)
                if response.status_code == 200:
                    resp = response.json()
                    if resp["msg"] == "success":
                        data = resp['data']
                        print("获取到学生信息")
                        print(
                            f"学校:{data['schoolName']} \n专业:{data['majorName']} \n班级:{data['className']} \n姓名:{data['realName']}")
                        self.stuMsg = data
                        return True
                    else:
                        print(resp)
                        return False
                else:
                    print(f"访问出现问题：code:{response.status_code},Msg:{response.text}")
                    return False
            except requests.exceptions.RequestException as e:
                print(f"请求失败，错误信息：{e}")
                retries += 1
                if retries < self.maxReteies:
                    print(f"等待{self.delay}秒后重试...")
                    time.sleep(self.delay)
                else:
                    print("打到最大重试次数，请求失败")
                    return False

    def get_AllCourses(self):
        """
        获取课程信息
        :return:
        """
        print("==========获取所有课程==========")
        url = f"{self.url}/servicehall/courseInfo/getCourseInfoStu?_t={self.timestamp()}&limit=100&page=1&chargeStatus=1"
        retries = 0
        while retries < self.maxReteies:
            try:
                response = requests.get(url, headers=self.headers, verify=False)
                if response.status_code == 200:
                    resp = response.json()
                    if resp["msg"] == "success":
                        courseData = resp['data']['list']
                        self.courseData = courseData
                        for course in courseData:
                            print(f"[{courseData.index(course)}]：{course['courseName']}")
                        return True
                    else:
                        print(resp)
                        return False
                else:
                    print(f"访问出现问题：code:{response.status_code},Msg:{response.text}")
                    return False
            except requests.exceptions.RequestException as e:
                print(f"请求失败，错误信息：{e}")
                retries += 1
                if retries < self.maxReteies:
                    print(f"等待{self.delay}秒后重试...")
                    time.sleep(self.delay)
                else:
                    print("打到最大重试次数，请求失败")
                    return False

    def get_CourseChapterList(self, courseId):
        """
        获取课程所有章节
        :param courseId:
        :return:
        """
        print("==========获取所有章节==========")
        url = f"{self.url}/servicehall/courseInfo/getHallCourseChapterList/{courseId}?_t={self.timestamp()}"
        retries = 0
        while retries < self.maxReteies:
            try:
                response = requests.get(url, headers=self.headers, verify=False)
                if response.status_code == 200:
                    resp = response.json()
                    if resp["msg"] == "success":
                        chapterData = resp['data']
                        self.chapterData = chapterData
                        for chapter in chapterData:
                            print(f"[{chapterData.index(chapter)}]: {chapter['directoryName']}")
                        return True
                    else:
                        print(resp)
                        return False
                else:
                    print(f"访问出现问题：code:{response.status_code},Msg:{response.text}")
                    return False
            except requests.exceptions.RequestException as e:
                print(f"请求失败，错误信息：{e}")
                retries += 1
                if retries < self.maxReteies:
                    print(f"等待{self.delay}秒后重试...")
                    time.sleep(self.delay)
                else:
                    print("打到最大重试次数，请求失败")
                    return False

    def recordVideoLog(self, courseId, courseName, directoryId, directoryNumber, videoId, videoName, duration,videoDurationStr):
        """
        提交视频进度
        :return:
        """
        url = f"{self.url}/video/recordVideoLog"
        payload = json.dumps({
            "playId": ''.join(random.choices(string.digits, k=19)),
            "playDuration": None,
            "playDurationStr": "",
            "courseId": courseId,
            "courseName": courseName,
            "directoryId": directoryId,
            "directoryNumber": directoryNumber,
            "videoId": videoId,
            "videoName": videoName,
            "currentTimes": duration,
            "duration": duration,
            "videoDurationStr": videoDurationStr,
            "isMobile": "N",
            "viewerId": self.stuMsg["id"],
            "viewerName": self.stuMsg["realName"],
            "schoolId": self.stuMsg["schoolId"],
            "schoolName": self.stuMsg["schoolName"],
            "deptId": self.stuMsg["deptId"],
            "deptName": self.stuMsg["deptName"],
            "classId": self.stuMsg["classId"],
            "className": self.stuMsg["className"],
            "lookDate": datetime.now().strftime('%Y-%m-%d'),
            "lookTime": datetime.now().strftime('%H:%M:%S'),
            "operatingSystem": "Mac",
            "browser": "chrome"
        })
        # print(json.loads(payload))
        retries = 0
        while retries < self.maxReteies:
            try:
                response = requests.post(url, data=payload, headers=self.headers, verify=False)
                if response.status_code == 200:
                    resp = response.json()
                    if resp["msg"] == "success":
                        print(f"课程:{courseName} 视频：{videoName} 进度提交成功")
                        return True
                    else:
                        print(resp)
                        return False
                else:
                    print(f"访问出现问题：code:{response.status_code},Msg:{response.text}")
                    return False
            except requests.exceptions.RequestException as e:
                print(f"请求失败，错误信息：{e}")
                retries += 1
                if retries < self.maxReteies:
                    print(f"等待{self.delay}秒后重试...")
                    time.sleep(self.delay)
                else:
                    print("打到最大重试次数，请求失败")
                    return False

if __name__ == '__main__':
    user = input("请输入账户:")
    pwd = input("请输入密码(默认为:yykt!123456):")
    if pwd == "":
        pwd = "yykt!123456"
    ip = "47.94.93.97"
    port = "81"
    mhys = mhys(user, pwd, f"http://{ip}:{port}")
    # 登录获取 token
    if (mhys.login()):
        print("登录成功")
        # 获取用户信息
        mhys.get_CenterInfo()
        # 获取所有课程
        while (True):
            mhys.get_AllCourses()
            choose = input("请输入选择的课程(输入886退出):")
            if int(choose) == 886:
                print("再见")
                break
            else:
                courseData = mhys.courseData[int(choose)]  # 课程数据
                print(f"课程名：{courseData['courseName']}")
                # 请求章节
                mhys.get_CourseChapterList(courseId=courseData["courseId"])
                chapterNumStr = input("请输入需要完成的章节(例如 0,1,2 输入-1表示全部选择,不输入退出):")
                chapters = []
                if chapterNumStr == "-1":
                    chapters = mhys.chapterData
                    print(chapters)
                elif chapterNumStr == "":
                    print("退出当前页面")
                    break
                else:
                    choose_nums = chapterNumStr.split(",")
                    for num in choose_nums:
                        chapters.append(mhys.chapterData[int(num)])
                for chapter in chapters:
                    print(f"==========章节：{chapter['directoryName']}==========")
                    for video in chapter['children']:
                        print(f"视频: {video['directoryName']}")
                        mhys.recordVideoLog(courseId=courseData["courseId"],
                                            courseName=courseData["courseName"],
                                            directoryId=video["directoryId"],
                                            directoryNumber=video["directoryNumber"],
                                            videoId=video["videoId"],
                                            videoName=video["videoName"],
                                            duration=video["videoDuration"],
                                            videoDurationStr=video["videoDurationStr"]
                                            )
                input("输入任意字符继续")


